package quick.api.app.service.article;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import quick.api.app.util.FormatArticleData;
import quick.api.app.util.FormatObjectExt;
import webdm.business.bean.Context;
import webdm.business.bean.ResponseDTO;
import webdm.business.component.AbstractPipelineComponent;
import webdm.business.util.ValueUtil;

import java.util.List;

public class FormatArticleList extends AbstractPipelineComponent {

    @Override
    public ResponseDTO process(Context context) {

        Object targetObj = ValueUtil.getValue(source, null, context.getParams());

        if(targetObj != null && targetObj instanceof JSONObject) {
            JSONObject result = (JSONObject)targetObj;//context.get("blog.article_list");

            if (result != null) {
                // 处理分页
                this.addPages(context, result);

                // 处理每篇文章
                JSONArray list = result.getJSONArray("list");

                if (list != null && list.size() > 0) {
                    list.forEach(item -> {
                        JSONObject obj = (JSONObject) item;
                        FormatObjectExt.format(obj);
                        FormatArticleData.formatArticle(obj);
                    });
                }
            }
        }


        return ResponseDTO.getSuccessInstance();
    }

    private void addPages (Context context, JSONObject pageContext) {

        int page = context.get("param.page", 0);
        int pageSize = context.get("param.page_size", 20);
        int total = pageContext.getIntValue("total");

        int pageTotal = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        int pre = page <= 1 ? 1 : page - 1;
        int next = page >= pageTotal ? pageTotal : page + 1;


        JSONArray pageList = new JSONArray();
        int len = 5;
        int startPage = Math.max(1, page - len);
        int endPage = Math.min(pageTotal, page + len);
        for(int i = startPage; i <= endPage; i++) {
            pageList.add(i);
        }
        JSONObject pageJson = new JSONObject();
        pageJson.put("pre", pre);
        pageJson.put("next", next);
        pageJson.put("list", pageList);

        context.set("page", pageJson);

    }
}
